#!/usr/bin/env python3
# policy/strategy_calculator.py
# 策略计算：捕获检查、移动决策
import numpy as np

import logging

logger = logging.getLogger(__name__)


class StrategyCalculator:
    def __init__(self, adj_matrix, f_matrix, dist_3d=None, dbin_available=False):
        self.adj_matrix = adj_matrix
        self.f_matrix = f_matrix
        self.dist_3d = dist_3d
        self.dbin_available = dbin_available

    def is_captured(self, evader_node, p1_node, p2_node):
        """检查捕获"""
        if evader_node == p1_node or evader_node == p2_node:
            return True
        if (
            self.adj_matrix[evader_node][p1_node] == 1
            or self.adj_matrix[evader_node][p2_node] == 1
        ):
            return True
        return False

    def cond1(self, p1, p2, l):
        """l邻接p1或p2"""
        return self.adj_matrix[l][p1] == 1 or self.adj_matrix[l][p2] == 1

    def get_neighbors(self, node_id):
        """获取邻居"""
        neighbors = []
        for j in range(len(self.adj_matrix)):
            if self.adj_matrix[node_id][j] == 1:
                neighbors.append(j)
        return neighbors

    def calculate_evader_move(self, evader_node, p1_node, p2_node):
        """独立计算逃避者移动（本地运算）"""
        if not self.dbin_available:
            return evader_node
        evader_neighbors = self.get_neighbors(evader_node)
        best_evader = evader_node
        max_value = -1
        best_dist_sum = float("-inf")
        for e_next in evader_neighbors:
            value = self.dist_3d[p1_node + 1][p2_node + 1][e_next + 1]
            dist_sum = self.f_matrix[p1_node][e_next] + self.f_matrix[p2_node][e_next]
            if value > max_value or (value == max_value and dist_sum > best_dist_sum):
                max_value = value
                best_evader = e_next
                best_dist_sum = dist_sum
        return best_evader

    def _remote_calculate_pursuers_move(
        self, evader_node, p1_node, p2_node, remote_server
    ):
        """远程追捕者移动"""
        p1_next, p2_next = remote_server.calculate_pursuers_move(
            evader_node, p1_node, p2_node
        )
        return p1_next, p2_next

    def visible(self, p1, p2, l):
        """可见性检查（辅助）"""
        if self.f_matrix[p1][l] <= 4:  # obs_dist 默认
            return True
        if self.f_matrix[p2][l] <= 4:
            return True
        return False
